package wss;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.http.websocketx.WebSocket13FrameDecoder;
import io.netty.handler.codec.http.websocketx.WebSocket13FrameEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslHandler;
import test.ClientHandler;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;

/**
 * @author 于振晗
 * @title: OkExWebclientClient
 * @description: TODO
 * @date 2021年11月27日
 * @path wss
 */
public class OkExWebSockettClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup work = new NioEventLoopGroup();
        ClientHandler clientHandler = new ClientHandler();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(work)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
//                        SSLContext sslContext = OkExWebSockettClient.createSSLContext("JKS","C://Users//Xiaojiuc//Desktop//wss.jks","netty123");
                        //SSLEngine 此类允许使用ssl安全套接层协议进行安全通信
//                        SSLEngine engine = sslContext.createSSLEngine();

                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline
//                                .addLast(new SslHandler(engine))
                                .addLast(new LoggingHandler(LogLevel.INFO))
                                .addLast(new WebSocket13FrameDecoder(false, true, 1024))
                                .addLast(new WebSocket13FrameEncoder(true))
                                .addLast(new WebSocketServerProtocolHandler("/ws/v5/public"))
                                .addLast(clientHandler);
                    }
                });
        // wss://wspri.coinall.ltd:8443/ws/v5/public
        ChannelFuture sync = bootstrap.connect("wspri.coinall.ltd", 8443).sync();

        String str = "{ \"op\": \"subscribe\", \"args\": [ { \"channel\": \"tickers-3s\", \"instId\": \"ETH-USDT\" } ] }";
        System.out.println(clientHandler);
//        clientHandler.ctx.writeAndFlush(str);

    }
}

